package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"we-chat/cache"
	"we-chat/models"
	pkg2 "we-chat/pkg"

	"we-chat/userrpc/internal/svc"
	"we-chat/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *userrpc.RegisterRequest) (*userrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	data, _ := cache.Rdb.Get(l.ctx, "send"+in.Mobile).Result()
	if in.SendSmsCode != data {
		return nil, errors.New("短信验证码错误请重新输入")
	}
	user := models.User{
		Model:    gorm.Model{},
		Mobile:   in.Mobile,
		Password: pkg2.Md5Str(in.Password),
		Name:     in.Name,
		Address:  in.Address,
		Title:    in.Title,
	}
	models.DB.Create(&user)
	return &userrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
